require 'rubytorrent'
require 'btcollection'
require 'btcontroller'
require 'btwrapper'
class QueuedDownload < ActiveRecord::Base
  attr :bt
  has_one :episode
  def get_episode
    Episode.find(self.episode_id)
  end
  
  def start_download
    episode = Episode.find(self.episode_id)
    url = episode.torrent_url
    dest = Configuration.find(:first).torrent_files_root + "/" + "#{episode.get_show.title.gsub(/ /, "-")}_#{episode.season}_#{episode.episode}.avi"
#    mi = RubyTorrent::MetaInfo.from_location(url)
#    package = RubyTorrent::Package.new(mi, dest) 
#    port = BTController.instance.next_port
#    logger.debug("Startind download on port #{port}")
    (BTController.instance).btcollection[self.id] = BTWrapper.new(episode, url, dest)
    (BTController.instance).btcollection[self.id].start_download
    episode.torrent_status = "downloading"
    episode.save
  end

  def completed_handler
  end

  def bt
    (BTController.instance).btcollection[self.id]
  end
end
